Page({
  data: {
    formData: { 
      name: '',
      phone: '',
      region: '',
      detailAddress: ''
    },
    region: [],
    index: -1
  },

  onLoad(options) {
    if (options.index) {
      const index = parseInt(options.index);
      const addressList = wx.getStorageSync('addressList') || [];
      const address = addressList[index];
      this.setData({
        formData: address,
        index: index
      });
    }
  },

  onInput(e) {
    const field = e.currentTarget.dataset.field;
    this.setData({
      [`formData.${field}`]: e.detail.value
    });
  },

  bindRegionChange(e) {
    const region = e.detail.value.join('-');
    this.setData({
      'formData.region': region
    });
  },

  onSubmit() {
    const formData = this.data.formData;
    
    // 验证手机号格式
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(formData.phone)) {
      wx.showToast({ title: '手机号格式不正确', icon: 'none' });
      return;
    }

    const addressList = wx.getStorageSync('addressList') || [];
    if (this.data.index >= 0) {
      // 编辑地址
      addressList[this.data.index] = formData;
      wx.showToast({ title: '地址编辑成功', icon: 'success' });
    } else {
      // 添加新地址
      if (addressList.length === 0) {
        formData.isDefault = true;
      }
      addressList.push(formData);
      wx.showToast({ title: '地址添加成功', icon: 'success' });
    }

    wx.setStorageSync('addressList', addressList);
    wx.navigateBack();
  }
});